package com.declum.archon.chunkserver.manager.disk.chunk;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


public class ChunkMetaDB extends HashMap<String, ChunkInfo> {

	ChunkMetaLogger logger;
	String dirpath;

	private ChunkMetaDB() {
		super();
	}

	public static ChunkMetaDB getInstance(String path) throws IOException {

		ChunkMetaDB chunkMetaDB = new ChunkMetaDB();
		chunkMetaDB.logger = ChunkMetaLogger.getInstance(path);
		chunkMetaDB.dirpath = path;
		chunkMetaDB.initialize();
		return chunkMetaDB;
	}

	private void initialize() {
		ChunkInfo info;
		for (String chunkid : this.logger.getAvailableChunks()) {
			info = ChunkInfo.getInstance(chunkid, this.dirpath);
			super.put(chunkid, info);
		}
	}

	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = 1L;

	@Override
	public void clear() {
		// super.clear();
		throw new RuntimeException("Cannot be used");
	}

	@Override
	public ChunkInfo put(String key, ChunkInfo value) {
		if (!value.isResolved()) {
			try {
				value.resolve();
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}
		try {
			this.logger.addChunkLog(key);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		return super.put(key, value);
	}

	@Override
	public void putAll(Map<? extends String, ? extends ChunkInfo> m) {
		throw new RuntimeException("Cannot be used");
		// super.putAll(m);
	}

	@Override
	public ChunkInfo remove(Object key) {
		try {
			this.logger.removeChunkLog(key.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return super.remove(key);
	}

}
